package com.fang.networkdisk.filter;

import com.fang.common.common.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Description
 * @Author Bernie_fang
 * @Date 2025/5/27 22:18
 **/
public class LogFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        // 从请求头获取Trace ID，若不存在则生成新的
        String traceId = httpRequest.getHeader(CommonConstants.CommonRequest.TRACE_ID_HEADER);
        if (StringUtils.isBlank(traceId)) {
            traceId = httpRequest.getHeader(CommonConstants.CommonRequest.TRACE_ID);
        }

        // 将Trace ID存入MDC
        MDC.put(CommonConstants.CommonRequest.TRACE_ID, traceId);

        try {
            chain.doFilter(request, response);
        } finally {
            // 确保请求结束后清理MDC，避免内存泄漏
            MDC.remove(CommonConstants.CommonRequest.TRACE_ID);
        }
    }

}